<!-- 高压用户变更页面弹窗 -->
<template>
  <div>
    <el-dialog :title="bgTitle" :visible.sync="show" :close-on-click-modal="false" width="900px" top="6vh" v-dialogDrag @close="cancel()">
      <div class="dialog-container">
        <el-form :model="bgForm" size="small" :rules="FormRules" ref="bgForm" label-width="150px">
          <el-row>
            <el-col :span="11">
              <el-form-item label="原单位编码">
                <el-input v-model="oldForm.dwbm" disabled></el-input>
              </el-form-item>

              <el-form-item label="原单位名称">
                <el-input v-model="oldForm.dwmc" disabled></el-input>
              </el-form-item>

              <el-form-item label="原用户编码">
                <el-input v-model="oldForm.yhbm" disabled></el-input>
              </el-form-item>

              <el-form-item label="原用户名称">
                <el-input v-model="oldForm.yhmc" disabled></el-input>
              </el-form-item>

              <el-form-item label="原电缆长度(kM)">
                <el-input v-model="oldForm.dlcd" disabled></el-input>
              </el-form-item>

              <el-form-item label="原架空裸导线(kM)">
                <el-input v-model="oldForm.jkcd" disabled></el-input>
              </el-form-item>

              <el-form-item label="原变压器台数">
                <el-input v-model="oldForm.bts" disabled></el-input>
              </el-form-item>

              <el-form-item label="原变压器容量(kVA)">
                <el-input v-model="oldForm.brl" disabled></el-input>
              </el-form-item>

              <el-form-item label="原电压等级(kV)">
                <el-input v-model="oldForm.dydj" disabled></el-input>
              </el-form-item>

              <el-form-item label="">（注：变更内容从变更日期当日生效）</el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="新单位编码" prop="dwbm">
                <el-input v-model="bgForm.dwbm" disabled>
                  <el-button slot="append" type="primary" class="button-choose" @click="chooseDwbm">选择</el-button>
                </el-input>
              </el-form-item>

              <el-form-item label="新单位名称" prop="dwmc">
                <el-input v-model="bgForm.dwmc" disabled></el-input>
              </el-form-item>

              <el-form-item label="新用户编码" prop="yhbm">
                <el-input v-model="bgForm.yhbm"></el-input>
              </el-form-item>

              <el-form-item label="新用户名称" prop="yhmc">
                <el-input v-model="bgForm.yhmc"></el-input>
              </el-form-item>

              <el-form-item label="新电缆长度(kM)" prop="dlcd">
                <el-input v-model="bgForm.dlcd" @change="getXlhj"></el-input>
              </el-form-item>

              <el-form-item label="新架空裸导线(kM)" prop="jkcd">
                <el-input v-model="bgForm.jkcd" @change="getXlhj"></el-input>
              </el-form-item>

              <el-form-item label="新变压器台数" prop="bts">
                <el-input v-model="bgForm.bts"></el-input>
              </el-form-item>

              <el-form-item label="新变压器容量(kVA)" prop="brl">
                <el-input v-model="bgForm.brl"></el-input>
              </el-form-item>

              <el-form-item label="新电压等级(kV)" prop="dydjm">
                <el-select v-model="bgForm.dydjm" @change="getDydj" style="width:100%">
                  <el-option
                    v-for="item in dydjCombo"
                    :key="item.value"
                    :label="item.text"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="变更日期" prop="tyrq">
                <el-date-picker type="date" v-model="bgForm.tyrq" @change="getZcrq" value-format="yyyy-MM-dd" style="width:100%"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="foot-container">
        <el-button type="primary" size="mini" @click="change('bgForm')">确 定</el-button>
        <el-button type="primary" size="mini" @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择单位编码 -->
    <GetDwbm :treeObj="treeObj" ref="getDwbmRef" @handleGetDwbm="handleGetDwbm"></GetDwbm>
  </div>
</template>

<script>
  import { getDictCombo } from "@/api/tools/dict";
  import { checkChar } from "@/utils/formValidate";
  import { DateDifference,checkSpecialKey,floatAdd } from "@/utils/validate";
  import { getZcgyyhsjById,checkUnique,changeZcgyyhsj } from "@/api/sjwh/zcgy";
  import { getUserInfo } from "@/utils/utilInfo.js";
  import GetDwbm from "@/dialogCommom/GetDwbm"

  export default {
    name: 'zcgyyhbg',
    components: {
      GetDwbm
    },
    data() {
      // 验证用户编码唯一
      const validateYhbm = (rule, value, callback) => {
        if (value) {
          let reg = /^([\u4e00-\u9fa5]{2})([0-9]{3})([\s\S]{0,7})$/
          if (checkSpecialKey(value)) {
            if (reg.test(value)) {
              let vo = {
                dwbm: this.bgForm.dwbm,
                zcrq: this.bgForm.zcrq,
                yhbm: value,
                oid: this.bgForm.id,
              }
              // 用户编码唯一性验证
              checkUnique(vo).then(res => {
                if (res.code == 0 && res.data) {
                  callback()
                } else {
                  callback('用户编码已经存在')
                }
              })
            } else {
              callback('2汉字+3数字+0~7字符')
            }
          } else {
            callback('禁止输入空格~!#$%^&等特殊字符')
          }
        }
      }
      // 4位整数验证
      const numberLen4 = (rule, value, callback) => {
        let val = value + ''
        if (val) {
          if (/(^([1-9]{1})([0-9]{0,3})$)|(^0$)/.test(val)) {
            callback()
          } else {
            callback('精度：4位整数')
          }
        }
      }
      // 10位整数验证
      const numberLen10 = (rule, value, callback) => {
        let val = value + ''
        if (val) {
          if (/(^([1-9]{1})([0-9]{0,9})$)|(^0$)/.test(val)) {
            callback()
          } else {
            callback('精度：10位整数')
          }
        }
      }
      // 6位整数数6位小数验证
      const floatLen66 = (rule, value, callback) => {
        let val = value + ''
        if (val) {
          let reg = /(^([1-9]{1})([0-9]{0,5})$)|(^([1-9]{1})([0-9]{0,5})[\.]{1}([0-9]{1,6})$)|(^0[\.]{1}[0-9]{1,6}$)|(^0$)/
          if (reg.test(val)) {
            callback()
          } else {
            callback('精度：整数6位，小数6位')
          }
        }
      }
      return {
        bgTitle:'高压用户变更',
        show: false,
        dydjCombo: [],
        oldForm: {
          dwbm: '',
          dwmc: '',
          yhbm: '',
          yhmc: '',
          dydj: '',
          dlcd: '',
          jkcd: '',
          bts: '',
          brl: '',
        },
        bgForm: {
          dwbm: '',
          dwmc: '',
          yhbm: '',
          yhmc: '',
          dydjm: '',
          dlcd: '',
          jkcd: '',
          bts: '',
          brl: '',
          tyrq: '', // 变更日期
        },
        zcrq: '', //原用户注册日期
        FormRules: {
          yhbm: [
            {required: true, message: '请输入用户编码', trigger: 'blur'},
            {validator: validateYhbm, trigger: 'blur'}
          ],
          yhmc: [
            {required: true, message: '请填写用户名称', trigger: 'blur'},
            {validator: checkChar, trigger: 'blur'}
          ],
          dlcd: [
            {required: true, message: '请填写电缆线路长度', trigger: 'blur'},
            {validator: floatLen66, trigger: 'blur'}
          ],
          jkcd: [
            {required: true, message: '请填写架空线路长度', trigger: 'blur'},
            {validator: floatLen66, trigger: 'blur'}
          ],
          bts: [
            {required: true, message: '请填写变压器台数', trigger: 'blur'},
            {validator: numberLen4, trigger: 'blur'}
          ],
          brl: [
            {required: true, message: '请填写变压器容量', trigger: 'blur'},
            {validator: numberLen10, trigger: 'blur'}
          ],
          dydjm: [{required: true, message: '请选择电压等级', trigger: 'blur'}],
          tyrq: [{required: true, message: '请选择变更日期', trigger: 'blur'}],
        },
        treeObj: { // 传给选择单位编码组件的值
          type: 'radio',
          dwbm: ''
        }
      }
    },
    props: {
      bgData: {
        type: Object,
        default: function() {
          return {};
        }
      }
    },
    watch: {
      bgData: {
        deep: true,
        handler(newVal, oldVal) {
          if (newVal.show) {
            const that = this
            that.show = newVal.show
            that.getFormData(newVal.id) // 根据ID查询数据
            this.dictOptData(); // 查询字典数据
          }
        }
      }
    },

    created() {
    },

    mounted() {

    },

    methods: {
      // 获取表单数据
      getFormData(id) {
        const that = this
        getZcgyyhsjById(id).then(res => {
          if (res.code == 0) {
            that.bgForm = res.data;
            // that.oldForm = res.data; 此处不能直接等 会造成bgForm和oldForm联动
            that.oldForm = {
              dwbm: res.data.dwbm,
              dwmc: res.data.dwmc,
              yhbm: res.data.yhbm,
              yhmc: res.data.yhmc,
              dydj: res.data.dydj,
              dlcd: res.data.dlcd,
              jkcd: res.data.jkcd,
              bts: res.data.bts,
              brl: res.data.brl,
            },
            that.zcrq = res.data.zcrq;
            that.bgForm.czy = getUserInfo.userName;
            that.bgForm.tyrq = '';
          } else {
            that.$message.error(res.message)
          }
        })
      },
      // 变更保存
      change() {
        const that = this
        that.$refs['bgForm'].validate((valid) => {
          if(valid) {
            if(that.compare()){
              that.$message.warning("请至少变更一个参数！");
              return;
            }
            if(DateDifference(that.bgForm.tyrq, that.zcrq) < 2){
              that.$message.warning("变更日期至少大于等于注册日期2天！");
              return;
            }
            return;
            // 提交数据
            let zcGyyhsj = that.bgForm;
            changeZcgyyhsj({zcGyyhsj}).then(res => {
              if (res.code == 0) {
                that.$message.success( "任务保存成功！");
                that.cancel();
                that.$parent.refresh(); // 调用父页面方法
              } else {
                that.$message.error("任务保存失败！");
              }
            });
          }else{
            that.$message.warning( "请检查填写数据项是否缺失或错误！");
          }
        });
      },
      cancel() {
        const that = this
        that.show = false;
        that.$refs['bgForm'].resetFields();  // 重置表单
        that.oldForm = {};
        that.bgForm = {};
      },
      // 获取字典下拉数据
      async dictOptData() {
        let dydjRes = await getDictCombo({"typeCode":"dict_dydj_gy"});
        if(dydjRes.code == 0){
          this.dydjCombo = dydjRes.data;
        }
      },
      // 选择单位编码树
      chooseDwbm() {
        const that = this
        let czdw = JSON.parse(sessionStorage.getItem('czdwinfo'))
        if(czdw.length >= 11){
          that.treeObj.dwbm = czdw
        }else{
          let treeNode = JSON.parse(sessionStorage.getItem('treeNode'))
          that.treeObj.dwbm = treeNode.dwbm.substring(0,11)
        }
        that.$refs.getDwbmRef.openDwbm()
      },
      // 单位编码回传
      handleGetDwbm(val){
        const that = this
        if (val.length == 0) {
          that.$message.warning('只能选择一个单位编码！')
          return;
        }
        if (val.data.dwjb < 4) {
          that.$message.warning('请选择局厂及以下单位！')
          return;
        }
        that.bgForm.dwbm = val.data.dwbm;
        that.bgForm.dwmc = val.data.dwmc.split(" ")[1];
      },
      getXlhj() {
        const that = this
        let dlcd = 0;
        let jkcd = 0;
        if(that.bgForm.dlcd!=""){
          dlcd = parseFloat(that.bgForm.dlcd);
        }
        if(that.bgForm.jkcd!=""){
          jkcd = parseFloat(that.bgForm.jkcd);
        }
        that.bgForm.xlhj = floatAdd(dlcd,jkcd);
      },
      getSdyrl() {
        const that = this;
        if(that.bgForm.issdy == "1" && this.bgForm.brl != ""){
          that.bgForm.sdyrl = that.bgForm.brl;
        }else{
          that.bgForm.sdyrl = 0;
        }
      },
      getDydj(val){
        const that = this
        let obj = {};
        obj = that.dydjCombo.find((item)=>{
          return item.value === val; // 筛选出匹配数据
        });
        that.bgForm.dydj = obj.text;
      },
      getZcrq(val){
        this.bgForm.zcrq = val;
      },
      // 比较参数是否有变化
      compare(){
        const that = this
        var propNames = Object.getOwnPropertyNames(this.oldForm);
        for (var i = 0; i < propNames.length-1; i++) { // -1去除 __ob__属性
          var propName = propNames[i];
          //console.log(that.oldForm[propName],that.bgForm[propName])
          if (that.oldForm[propName] != that.bgForm[propName]) {
            return false;
          }
        }
        return true;
      },
    }
  }
</script>

<style scoped lang='scss'>
  /deep/ .el-dialog__body {
    padding-top: 20px;
    padding-bottom: 1px;
    border-top: 1px solid #e8eaec;
    border-bottom: 1px solid #e8eaec;
  }
  /deep/ .el-dialog__header {
    padding: 10px 10px 10px;
  }
  /deep/ .el-dialog__footer {
    padding: 10px 10px 10px;
  }
  .dialog-container{
    /*height: 100%;*/
    height: 60vh;
    overflow: auto;
  }
  .button-choose {
    background-color: #409EFF !important;
    border-color: #409EFF !important;
    color: #ffffff !important;
  }
</style>
